package com.jyk.blog.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jyk.blog.po.Blog;
import com.jyk.blog.po.Comment;
import com.jyk.blog.po.Tag;
import com.jyk.blog.po.User;
import com.jyk.blog.service.*;
import com.jyk.blog.util.TimeUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    BlogService blogService;
    @Autowired
    TypeService typeService;
    @Autowired
    TagService tagService;
    @Autowired
    BlogTagService blogTagService;
    @Autowired
    CommentService commentService;

    @RequestMapping(value = {"/index", "/"})
    public String index(HttpSession session, Model model, @RequestParam(defaultValue = "1", required = true, value = "pageNo") Integer pageNo) {
        // 分类和标签信息
        model.addAttribute("typeList", typeService.queryAll());
        model.addAttribute("tagList", tagService.queryAll());
        model.addAttribute("userService", userService);

        User user = (User) session.getAttribute("user");
        if (user != null){
            String permission = userService.getPermission(user);
            if (permission != null && permission.equals("admin")){
                model.addAttribute("permission", "admin");
            }
        }
        //博客信息列表
        Integer pageSize = 4;
        PageHelper.startPage(pageNo, pageSize, "nid desc");
        List<Blog> blogList = blogService.queryAll();
        PageInfo<Blog> pageInfo = new PageInfo<>(blogList);
        model.addAttribute("blogList", pageInfo);

        return "index";
    }

    @RequestMapping("/login")
    public String login(Model model) {
        // 分类和标签信息
        model.addAttribute("typeList", typeService.queryAll());
        model.addAttribute("tagList", tagService.queryAll());
        return "login";
    }

    @RequestMapping("/loginC")
    public String loginC(Model model, HttpSession session, String name, String pwd) {
        // 分类和标签信息
        model.addAttribute("typeList", typeService.queryAll());
        model.addAttribute("tagList", tagService.queryAll());
        session.setAttribute("userWrong", null);
        session.setAttribute("passwordWrong", null);

        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken userToken = new UsernamePasswordToken(name, pwd);
        try {
            subject.login(userToken);
            session.setAttribute("user", userService.queryByName(name));
            return "redirect:/index";
        } catch (UnknownAccountException e) {//用户名不存在
            e.printStackTrace();
            session.setAttribute("userWrong", "y");
            return "login";
        } catch (IncorrectCredentialsException e) {//密码错误
            session.setAttribute("passwordWrong", "y");
            return "login";
        }
    }

    @RequestMapping("/logout")
    public String loginOut(HttpSession session) {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            subject.logout();
        }
        return "redirect:/index";
    }

    @RequestMapping("/register")
    public String register(Model model) {
        // 分类和标签信息
        model.addAttribute("typeList", typeService.queryAll());
        model.addAttribute("tagList", tagService.queryAll());
        return "register";
    }

    @RequestMapping("/registerC")
    public String registerC(Model model, HttpSession session, String name, String pwd, String pwd2, String email) {
        // 分类和标签信息
        model.addAttribute("typeList", typeService.queryAll());
        model.addAttribute("tagList", tagService.queryAll());

        if (userService.queryByEmail(email) != null) {
            session.setAttribute("emailRepeat", "y");
            return "register";
        } else {
            session.setAttribute("emailRepeat", null);
        }

        if (userService.queryByName(name) != null) {
            session.setAttribute("nameRepeat", "y");
            return "register";
        } else {
            session.setAttribute("nameRepeat", null);
        }

        if (!pwd.equals(pwd2)) {
            session.setAttribute("passwordRepeat", "y");
            return "register";
        } else {
            session.setAttribute("passwordRepeat", null);
        }

        userService.insert(new User(name, pwd, email, TimeUtil.getCurTime()));

        session.setAttribute("user", userService.queryByName(name));
        System.out.println(userService.queryByName(name));
        System.out.println("注册成功");

        return "redirect:/index";
    }

    @RequestMapping("/edit")
    public String edit(Model model, HttpSession session) {
        // 分类和标签信息
        model.addAttribute("typeList", typeService.queryAll());
        model.addAttribute("tagList", tagService.queryAll());
        return "editBlog";
    }

    @RequestMapping("/editC")
    public String editC(HttpSession session, String type, Integer[] tags, String title, String subtitle, String content) {
        // 添加博客
        User user = (User) session.getAttribute("user");
        String curTime = TimeUtil.getCurTime();
        Blog blog = new Blog(title, subtitle, content, curTime, user.getNid(), typeService.queryByName(type).getNid());
        blogService.addOne(blog);

        // 添加博客标签信息
        Blog b = blogService.queryByTime(curTime, user.getNid());
        if (tags != null) {
            for (Integer tag : tags) {
                blogTagService.insertOne(b.getNid(), tag);
            }
        }
        return "redirect:/index";
    }

    @RequestMapping("/blogDetail")
    public String blogDetail(Integer id, Model model) {
        // 分类和标签信息
        model.addAttribute("typeList", typeService.queryAll());
        model.addAttribute("tagList", tagService.queryAll());
        model.addAttribute("userService", userService);

        List<Tag> tags = blogTagService.queryByBlog(id);
        String tagInfo = "";
        for (Tag tag : tags) {
            tagInfo = tagInfo + tag.getName() + "  ";
        }
        model.addAttribute("tagInfo", tagInfo);

        Blog blog = blogService.queryById(id);
        model.addAttribute("blog", blog);

        model.addAttribute("contents", blog.getContent().split("\\s+"));

        model.addAttribute("comments", commentService.queryByBlog(id));
        return "blogDetail";
    }

    @RequestMapping("/showByType")
    public String showByType(Integer typeID, Model model, @RequestParam(defaultValue = "1", required = true, value = "pageNo") Integer pageNo) {
        // 分类和标签信息
        model.addAttribute("typeList", typeService.queryAll());
        model.addAttribute("tagList", tagService.queryAll());
        model.addAttribute("userService", userService);

        //博客信息列表
        Integer pageSize = 4;
        PageHelper.startPage(pageNo, pageSize, "nid desc");
        List<Blog> blogList = blogService.queryByType(typeID);
        PageInfo<Blog> pageInfo = new PageInfo<>(blogList);
        model.addAttribute("blogList", pageInfo);

        model.addAttribute("type", typeService.queryById(typeID));
        return "showByType";
    }

    @RequestMapping("/showByTag")
    public String showByTag(Integer tagID, Model model, @RequestParam(defaultValue = "1", required = true, value = "pageNo") Integer pageNo) {
        // 分类和标签信息
        model.addAttribute("typeList", typeService.queryAll());
        model.addAttribute("tagList", tagService.queryAll());
        model.addAttribute("userService", userService);

        //博客信息列表
        Integer pageSize = 4;
        PageHelper.startPage(pageNo, pageSize, "nid desc");
        List<Blog> blogList = blogTagService.queryByTag(tagID);
        PageInfo<Blog> pageInfo = new PageInfo<>(blogList);
        model.addAttribute("blogList", pageInfo);

        model.addAttribute("tag", tagService.queryById(tagID));
        return "showByTag";
    }

    @RequestMapping("/comment")
    public String comment(HttpSession session, Integer blogID, Integer userID, String comment) {
        Comment MyComment = new Comment(comment, TimeUtil.getCurTime(), blogID, userID);
        commentService.insertOne(MyComment);
        return "redirect:/blogDetail?id=" + blogID;
    }

    @RequestMapping("/info")
    public String info(HttpSession session, Model model) {
        // 分类和标签信息
        model.addAttribute("typeList", typeService.queryAll());
        model.addAttribute("tagList", tagService.queryAll());
        model.addAttribute("userService", userService);


        return "info";
    }

    @RequestMapping("/info_blog")
    public String info_blog(HttpSession session, Model model, @RequestParam(defaultValue = "1", required = true, value = "pageNo") Integer pageNo) {
        // 分类和标签信息
        model.addAttribute("typeList", typeService.queryAll());
        model.addAttribute("tagList", tagService.queryAll());
        model.addAttribute("userService", userService);

        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:login";
        }

        Integer pageSize = 4;
        PageHelper.startPage(pageNo, pageSize, "nid desc");
        List<Blog> blogList = blogService.queryByUser(user.getNid());
        PageInfo<Blog> pageInfo = new PageInfo<>(blogList);
        model.addAttribute("blogList", pageInfo);

        return "info_blog";
    }
}
